require "Common/define"
require "Logic/Config"
require "Common/functions"
require "Net/towerHandler"
require "FairyGUI"
require "RedDots/RedDotsTrialHandler"
UIAdventureMain = {};
HelperFunc.SetUIEnv(UIAdventureMain)
local this = UIAdventureMain;

this._bfxwPlayTime = 500 -- 暴风峡湾入场动画持续时间(毫秒)
this._xyyzPlayTime = 2000 -- 旋云远征入场动画持续时间（毫秒）
this._mwclPlayTime = 1300 -- 迷雾长廊入场动画持续时间（毫秒）
this.gameObject = nil;
this.transform = nil;
this.LuaBehaviour = nil;

this.btn_Adventure1 = nil;
this.btn_Adventure2 = nil;
this.btn_Adventure3 = nil;
this.btn_Adventure4 = nil
this.btn_Adventure5 = nil
this.btn_Adventure9 = nil
this.btn_Adventure10 = nil
this.btnInvasion=nil
this.drawWrapper = nil;
this.spine = nil;
this.drawWrapper = nil;
this.hasInit = false
this.rankBattleCtrl = nil
this.timeTip = nil
this.nextTime_txt = nil
this.timeId = nil
this.btnInvasion={}
this.aniAdventure2 = nil;
this.aniAdventure2Back = nil;
this.teamCtrl=nil
function UIAdventureMain.Init()
    local name, packageName = getUIName(PanelNames.UIAdventureMain);
    panelMgr:Push(name, packageName, this.OnCreate, Config.useLocalUI);
end

function UIAdventureMain.OnCreate(obj)
    if not hasInit then
        hasInit = true
        aniAdventure2 = obj:GetTransition("Effect_EnterMythicDungeons");
        aniAdventure2Back = obj:GetTransition("Effect_Reset");
        aniAdventure3 = obj:GetTransition("Effect_ruhcang_mwclOut");
        aniAdventure4 = obj:GetTransition("Effect_ruhcang_xyyzOut");
        btn_Adventure1 = obj:GetChild("adventure1");
        btn_Adventure2 = obj:GetChild("adventure2");
        btn_Adventure3 = obj:GetChild("adventure3");
        btn_Adventure4 = obj:GetChild("adventure4");
        btn_Adventure5 = obj:GetChild("adventure5");
        btn_Adventure9 = obj:GetChild("adventure9");
        btn_Adventure10 = obj:GetChild("adventure10");
        this.btn_reward = obj:GetChild("btnReward")
        if this.btn_reward ~= nil then
            this.btn_reward.visible = false
        end
        btnInvasion=obj:GetChild("btnInvasion")
        teamCtrl=obj:GetController("teamOpen")
        teamCtrl.selectedIndex=1
        rankBattleCtrl = btn_Adventure9:GetController("rankbattle")
        timeTip = btn_Adventure9:GetChild("Text_Off")
        nextTime_txt = btn_Adventure9:GetChild("Text_TimeCount")
        this.Graph_UI_ruchang_rszd = obj:GetChild("Graph_UI_ruchang_rszd");
        this.Graph_UI_ruchang_bfxw = obj:GetChild("Graph_UI_ruchang_bfxw");
        this.Graph_UI_ruchang_xyyz = obj:GetChild("Graph_UI_ruchang_xyyz");
        this.Graph_UI_ruchang_mwcl = obj:GetChild("Graph_UI_ruchang_mwcl");
        this.par = {};
        this.parDraw = {};
        this.effList = {};
        table.insert(this.effList, {obj:GetChild("eff_ruchang_cw"), "UI_ruchang_cw"})
        for i = 1, #this.effList do
            resMgr:LoadModelPrefab("UIEff/"..this.effList[i][2], function(go)
                if this.parDraw[i] == nil then
                    this.parDraw[i] = GoWrapper.New()
                end
                if not HelperFunc.IsNull(this.par[i]) then
                    destroyImmediate(this.par[i])
                end
                this.par[i] = newObject(go);
                this.par[i]:SetActive(true);
                this.par[i]:AddComponent(TCanvas);
                this.par[i]:AddComponent(TChangeSortingOrder);
                Util.Lua_SetLocalScaleXYZ(this.par[i],1,1,1)
                Util.Lua_SetLocalRotationXYZ(this.par[i],0,0,0)
                this.parDraw[i]:SetWrapTarget(this.par[i], true)
                this.effList[i][1]:SetNativeObject(this.parDraw[i])
            end)
        end
        this.addEvent();
    end
    this.Refresh();
    this.refreshRealMan();

    UIRedDots.addViewListen(PanelNames.UIAdventureMain, "UIAdventureMain_btn_Adventure4", btn_Adventure4, Config.RedDotsType.ExpeditionAll);
    UIRedDots.addViewListen(PanelNames.UIAdventureMain, "UIAdventureMain_btn_Adventure5", btn_Adventure5, Config.RedDotsType.Trials);
    UIRedDots.addViewListen(PanelNames.UIAdventureMain, "UIAdventureMain_btn_Adventure1", btn_Adventure1, Config.RedDotsType.Arena);
    UIRedDots.addViewListen(PanelNames.UIAdventureMain, "UIAdventureMain_btn_Adventure2", btn_Adventure2, Config.RedDotsType.MythicDungeons);
    UIRedDots.addViewListen(PanelNames.UIAdventureMain, "UIAdventureMain_btn_Adventure3", btn_Adventure3, Config.RedDotsType.ClimbTower);
    UIRedDots.addViewListen(PanelNames.UIAdventureMain, "UIAdventureMain_btn_Adventure9", btn_Adventure9, Config.RedDotsType.RankBattle);
    UIRedDots.addViewListen(PanelNames.UIAdventureMain, "UIAdventureMain_btn_Adventure10", btn_Adventure10, Config.RedDotsType.RealMan);
    UIRedDots.addViewListen(PanelNames.UIAdventureMain, "UIAdventureMain_btn_Invasion", btnInvasion, Config.RedDotsType.InvasionBattle);
    logicMgr.FuncOpenManager.addStatusCtr(PanelNames.UIAdventureMain,Config.FuncOpenType.Arena, btn_Adventure1.name,btn_Adventure1);
    FuncOpenManager.addStatusCtr(PanelNames.UIAdventureMain,Config.FuncOpenType.Tower, btn_Adventure3.name,btn_Adventure3);
    FuncOpenManager.addStatusCtr(PanelNames.UIAdventureMain,Config.FuncOpenType.Mythic, btn_Adventure2.name,btn_Adventure2);
    FuncOpenManager.addStatusCtr(PanelNames.UIAdventureMain,Config.FuncOpenType.expedition, btn_Adventure4.name,btn_Adventure4);
    FuncOpenManager.addStatusCtr(PanelNames.UIAdventureMain,Config.FuncOpenType.trials, btn_Adventure5.name,btn_Adventure5);
    FuncOpenManager.addStatusCtr(PanelNames.UIAdventureMain,Config.FuncOpenType.RankBattle, btn_Adventure9.name,btn_Adventure9);
    FuncOpenManager.addStatusCtr(PanelNames.UIAdventureMain,Config.FuncOpenType.RealMan, btn_Adventure10.name,btn_Adventure10);
    FuncOpenManager.addStatusCtr(PanelNames.UIAdventureMain,Config.FuncOpenType.InvasionBattle, btnInvasion.name,btnInvasion);
    this.InitBtnInvasion()

end

function UIAdventureMain.OnDestroy()
    this.removeEvent();
    for k, v in pairs(this.par) do
        destroyImmediate(v)
    end
    this.par = {};
    hasInit = false
    this.DisPoseTimer()
    this.RemoveInvasionTimer()
end

function UIAdventureMain.addEvent()
    ListenEvent(Config.EventType.Fresh_AdventureMain, this.Refresh);
    ListenEvent(Config.EventType.Fresh_RealManRealManWar, this.refreshRealMan);
    btn_Adventure1.onClick:Add(this.OnClickAdventure1)
    btn_Adventure2.onClick:Add(this.OnClickAdventure2)
    btn_Adventure3.onClick:Add(this.OnClickAdventure3)
    btn_Adventure4.onClick:Add(this.OnClickAdventure4)
    btn_Adventure5.onClick:Add(this.OnClickAdventure5)
    btn_Adventure9.onClick:Add(this.OnClickAdventure9)
    btn_Adventure10.onClick:Add(this.OnClickAdventure10)
    btnInvasion.onClick:Add(this.OnClickInvasion)
    this.btn_reward.onClick:Add(this.onClickGetReward)
end

function UIAdventureMain.onClickGetReward()
    if this.last_click_offline_reward ~= nil and UnityEngineTime.realtimeSinceStartup - this.last_click_offline_reward < 1 then
        return
    end
    local baseInfo = logicMgr.ArenaManager.getCrossTeamBaseInfo()
    this.last_click_offline_reward = UnityEngineTime.realtimeSinceStartup
    if baseInfo and baseInfo.rank < 131 then
        if baseInfo.award > 0 then
            crossTeamArenaHandler.sendReqHighArenaGetAward()
            this.btn_reward.visible = false
        else
            UISysTips.AddMsg( string.format("没有可领取的%s", ItemManager.GetItemName(31)) )
        end
    end
end

function UIAdventureMain.InitBtnInvasion()
    --return
    local openTime = tonumber(logicMgr.CronMgr.GetNextDateTime(dataTable.getGlobalString(655),HelperFunc.GetServerTime()))
    local endTime = tonumber(logicMgr.CronMgr.GetNextDateTime(dataTable.getGlobalString(654),HelperFunc.GetServerTime()))
    local time =  HelperFunc.GetServerTime()
    local cntDnText=btnInvasion:GetChild("Text_TimeCount")
    local offText = btnInvasion:GetChild("Text_Off")
    local cntDnCtrl=btnInvasion:GetController("rankbattle")
    local endCntDn=endTime-time
    local function updateInvasionTime()
        if not (logicMgr.InvasionManager.IsOpen() and logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.InvasionBattle)) then
            if invasionTimer~=nil then
                utimer.remove(invasionTimer)
                invasionTimer=nil
            end
            offText.text = getLanguage("InvasionClose")
            cntDnCtrl.selectedIndex=1
        else
            cntDnCtrl.selectedIndex=2
            cntDnText.text = HelperFunc.GetSurpTimeStr(endCntDn)
        end
        endCntDn=endCntDn-1
    end

    updateInvasionTime()
    invasionTimer = utimer.timeCall(function()
        updateInvasionTime()
    end, 1000, -1)
end
function UIAdventureMain.OnClickInvasion()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.InvasionBattle,true,btnInvasion) then
        if logicMgr.InvasionManager.IsOpen() then
            InvasionHandler.ReqInitTeamBoss(2,1)
            InvasionHandler.ReqOpenHighReward(0)
            --logicMgr.InvasionManager.SetInvasionFirstOpen(0)
        else
            UISysTips.AddMsg(getLanguage("InvasionClose"))
        end
        --InvasionHandler.ReqInitTeamBoss(2,1)
    end
    logicMgr.InvasionManager.SetInvasionKicked(0)
end
function UIAdventureMain.removeEvent()
    if not hasInit then
        return
    end
    CloseEvent(Config.EventType.Fresh_AdventureMain, this.Refresh)
    CloseEvent(Config.EventType.Fresh_RealManRealManWar, this.refreshRealMan);
    btn_Adventure1.onClick:Remove(this.OnClickAdventure1)
    btn_Adventure2.onClick:Remove(this.OnClickAdventure2)
    btn_Adventure3.onClick:Remove(this.OnClickAdventure3)
    btn_Adventure4.onClick:Remove(this.OnClickAdventure4)
    btn_Adventure5.onClick:Remove(this.OnClickAdventure5)
    btn_Adventure9.onClick:Remove(this.OnClickAdventure9)
    btn_Adventure10.onClick:Remove(this.OnClickAdventure10)
    btnInvasion.onClick:Remove(this.OnClickInvasion)
end

function UIAdventureMain.OnEnable()
    if UIAdventureMain.aniAdventure2Back then
        UIAdventureMain.aniAdventure2Back:Play();
    end

    --if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.CrossTeamArena, false) then
    --    local baseInfo = logicMgr.ArenaManager.getCrossTeamBaseInfo()
    --    if baseInfo ~= nil and baseInfo.award <= 0 then
    --        crossTeamArenaHandler.sendReqHighArenaInfo()
    --    end
    --else
    --    if this.btn_reward ~= nil then
    --        this.btn_reward.visible = false
    --    end
    --end
    this.RefreshArenaAward();
end

function UIAdventureMain.OnDisable()
    CloseEvent(Config.EventType.Fresh_AdventureMain, this.Refresh);
    CloseEvent(Config.EventType.Fresh_RealManRealManWar, this.refreshRealMan);
    UIRedDots.removeViewEvent(PanelNames.UIAdventureMain)
    logicMgr.FuncOpenManager.removeStatusCtr(PanelNames.UIAdventureMain);
    this.DisPoseTimer()
    this.RemoveInvasionTimer()
end

function UIAdventureMain.RemoveInvasionTimer()
    if invasionTimer~=nil then
        utimer.remove(invasionTimer)
        invasionTimer=nil
    end
end

function UIAdventureMain.DisPoseTimer()
    if timeId then
        utimer.remove(timeId)
        timeId = nil
    end
    this.removeRealManTimer();
end

function UIAdventureMain.RefreshArenaAward()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.CrossTeamArena, false) then
        if logicMgr.ArenaManager.isGetCrossTeamAward() then
            if this.btn_reward ~= nil then
                this.btn_reward.visible = true
            end
        else
            if this.btn_reward ~= nil then
                this.btn_reward.visible = false
            end
        end
    else
        if this.btn_reward ~= nil then
            this.btn_reward.visible = false
        end
    end
end

function UIAdventureMain.Refresh()
    this.DisPoseTimer()
    -- this.RefreshArenaAward()
    btn_Adventure9.visible = logicMgr.RankBattleManager.isRankBattleOpen();
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.RankBattle) then
        local myInfo = logicMgr.RankBattleManager.GetMyInfo()
        if myInfo.nextTime then
            local nextTime = tonumber(tostring(myInfo.nextTime)) / 1000 - HelperFunc.GetServerTime()
            if myInfo.status == 1 then
                rankBattleCtrl.selectedIndex = 2
                nextTime_txt.text = timeToTimeFormat(nextTime)
                timeId = utimer.timeCall(function()
                    nextTime = tonumber(tostring(myInfo.nextTime)) / 1000 - HelperFunc.GetServerTime()
                    nextTime_txt.text = timeToTimeFormat(nextTime)
                    if nextTime <= 0 then
                        rankBattleCtrl.selectedIndex = 1
                        timeTip.text = getLanguage("RankTimeTips")
                        return true;
                    end
                end, 1000, -1)
            else
                rankBattleCtrl.selectedIndex = 1
                timeTip.text = getLanguage("RankTimeTips")
            end
        end
    else
        rankBattleCtrl.selectedIndex = 0
    end
end

--深渊试炼
function UIAdventureMain.refreshRealMan()
    this.removeRealManTimer();
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.RealMan) then
        local cntDnText=btn_Adventure10:GetChild("Text_TimeCount");
        local cntDnCtrl=btn_Adventure10:GetController("rankbattle");
        if logicMgr.RealManWarManager.isOpen() then
            cntDnCtrl.selectedIndex = 2;
            local realManWarInfo = logicMgr.RealManWarManager.getRealManWarInfo();
            if realManWarInfo ~= nil then
                local endCountDown = realManWarInfo.nextChangeStatusTime - HelperFunc.GetServerTime();
                realManTimer = utimer.timeCall(function()
                    if endCountDown <= 0 then
                        cntDnCtrl.selectedIndex=0
                        this.removeRealManTimer();
                    else
                        cntDnText.text = timeToTimeFormat(endCountDown);
                    end
                    endCountDown=endCountDown-1;
                end, 1000, -1);
                cntDnText.text = timeToTimeFormat(endCountDown);
            end
        else
            cntDnCtrl.selectedIndex = 0;
        end
    end
end

function UIAdventureMain.removeRealManTimer()
    if realManTimer~=nil then
        utimer.remove(realManTimer);
        realManTimer=nil;
    end
end

function UIAdventureMain.OnClickAdventure1()
    this.DisPoseTimer()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Arena, true,btn_Adventure1) then
        showUI(PanelNames.UIArenaMainEnter,true)
    end
end

function UIAdventureMain.OnClickAdventure2()
    this.DisPoseTimer()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Mythic, true,btn_Adventure2) then
        if not aniAdventure2.playing then
            UIHeadMenu.isNeedShowMask(true);
            aniAdventure2:Play(function()
                UIHeadMenu.isNeedShowMask();
                showUI(PanelNames.UIMythicDungonsPro,function ()
                    --进入后出战斗，会掉用 FightManager 2885行  showUI(PanelNames.UIMythicDungons)，会把这里的回调覆盖掉。在OnEnable里容错处理了
                    UIAdventureMain.aniAdventure2Back:Play();
                end,true);
            end);
        end
    end
end

function UIAdventureMain.OnClickAdventure3()
    this.DisPoseTimer()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Tower, true,btn_Adventure3) then
        --HelperFunc.OpenUILoading(function () showUI(PanelNames.UIClimbTower); end);

        resMgr:LoadModelPrefab("UIEff/UI_ruchang_mwcl_out", function(prefab)
            if this.effDrawWrapper3 == nil then
                this.effDrawWrapper3 = GoWrapper.New();
            end
            if this.eff3Obj ~= nil then
                destroyImmediate(this.eff3Obj);
                this.eff3Obj = nil
            end
            this.eff3Obj = newObject(prefab)
            this.effDrawWrapper3:SetWrapTarget(this.eff3Obj,false)
            Util.Lua_SetLocalRotationXYZ(this.eff3Obj.transform, 0, 0, 0);
            this.Graph_UI_ruchang_mwcl:SetNativeObject(this.effDrawWrapper3)
        end)
        utimer.timeCall(function ()
            --是否开启职业爬塔
            if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.TowerAdvaced, false) then
                showUI(PanelNames.UITowerMain)
            else
                showUI(PanelNames.UIClimbTower, nil, true)
            end
            UIHeadMenu.isNeedShowMask();
            if this.eff3Obj ~= nil then
                destroyImmediate(this.eff3Obj);
                this.eff3Obj = nil
            end
        end, this._mwclPlayTime, 1);
        --if not aniAdventure3.playing then
        --
        --end
        UIHeadMenu.isNeedShowMask(true);
        aniAdventure3:Play(function()
            aniAdventure3:PlayReverse()
        end);
    end
end
function UIAdventureMain.OnClickAdventure4()
    this.DisPoseTimer()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.expedition, true,btn_Adventure4) then
        UIHeadMenu.isNeedShowMask(true);
        resMgr:LoadModelPrefab("UIEff/UI_ruchang_xyyz_out", function(prefab)
            if this.effDrawWrapper1 == nil then
                this.effDrawWrapper1 = GoWrapper.New();
            end
            if this.effFire1Obj ~= nil then
                destroyImmediate(this.effFire1Obj);
                this.effFire1Obj = nil;
            end
            this.effFire1Obj = newObject(prefab)
            this.effDrawWrapper1:SetWrapTarget(this.effFire1Obj,false)
            Util.Lua_SetLocalRotationXYZ(this.effFire1Obj.transform, 0, 0, 0);
            this.Graph_UI_ruchang_xyyz:SetNativeObject(this.effDrawWrapper1)
        end)
        utimer.timeCall(function ()
            UIHeadMenu.isNeedShowMask();
            if this.effFire1Obj ~= nil then
                destroyImmediate(this.effFire1Obj);
                this.effFire1Obj = nil;
            end
        end, this._xyyzPlayTime, 1);
        if not aniAdventure4.playing then
            UIHeadMenu.isNeedShowMask(true);
            aniAdventure4:Play(function()
                logicMgr.UIShowManager.ShowExpeditionView()
                aniAdventure4:PlayReverse()
            end);
        end
    end
end

function UIAdventureMain.OnClickAdventure5()
    this.DisPoseTimer()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.trials, true,btn_Adventure5) then
        if not this.aniAdventure5Playing then
            UIHeadMenu.isNeedShowMask(true);
            resMgr:LoadModelPrefab("UIEff/UI_ruchang_bfxw", function(prefab)
                if this.effDrawWrapper5 == nil then
                    this.effDrawWrapper5 = GoWrapper.New();
                end
                if this.effFire5Obj ~= nil then
                    destroyImmediate(this.effFire5Obj);
                    this.effFire5Obj = nil
                end
                this.effFire5Obj = newObject(prefab)
                this.effDrawWrapper5:SetWrapTarget(this.effFire5Obj,false)
                Util.Lua_SetLocalRotationXYZ(this.effFire5Obj.transform, 0, 0, 0);
                this.Graph_UI_ruchang_rszd:SetNativeObject(this.effDrawWrapper5)
            end)
            this.aniAdventure5Playing = utimer.timeCall(function ()
                AudioManager.SetSwitch("Battle_SwitchGroup", "stormbay")
                -- showUI(PanelNames.UIChaosTest);
                showUI(PanelNames.UIChaosTestNew)
                UIHeadMenu.isNeedShowMask();
                if this.effFire5Obj ~= nil then
                    destroyImmediate(this.effFire5Obj);
                    this.effFire5Obj = nil
                end
                this.aniAdventure5Playing = nil;
            end, this._bfxwPlayTime, 1);
        end
    end
end

function UIAdventureMain.OnClickAdventure9()
    this.DisPoseTimer()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.RankBattle, true, btn_Adventure9) then
        AudioManager.SetSwitch("Battle_SwitchGroup", "origin")
        showUI(PanelNames.UIRankBattle);

    end
end

function UIAdventureMain.OnClickAdventure10()
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.RealMan, true, btn_Adventure10) then
        --AudioManager.SetSwitch("Battle_SwitchGroup", "origin");
        --if not logicMgr.RealManWarManager.isOpen() then
        --    UISysTips.AddMsg(getLanguage("战斗结束"));
        --    return;
        --end
        logicMgr.RealManWarManager.updateRealManOpenStatus();
        logicMgr.RealManWarManager.setEnterBattle(false);
        logicMgr.RealManWarManager.OpenSoloBattle(1);
    end
end

return UIAdventureMain;